package com.mano.mall.service.pay.impl;

import com.alibaba.fastjson.JSONObject;
import com.mano.mall.api.dto.pay.output.PayMentTransacDTO;
import com.mano.mall.api.pay.PayContextService;
import com.mano.mall.api.pay.PayMentTransacInfoService;
import com.mano.mall.common.base.BaseApiService;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.service.mapper.PaymentChannelMapper;
import com.mano.mall.service.mapper.entity.PaymentChannelEntity;
import com.mano.mall.service.strategy.PayStrategy;
import com.mano.mall.service.strategy.StrategyFactory;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PayContextServiceImpl extends BaseApiService<JSONObject> implements PayContextService {

	@Autowired
	private PaymentChannelMapper paymentChannelMapper;
	@Autowired
	private PayMentTransacInfoService payMentTransacInfoService;

	@Override
	@HystrixCommand(fallbackMethod = "defaultCallBackMethod")
	public BaseResponse<JSONObject> toPayHtml(String channelId, String payToken) {
		// 1.使用渠道id查询渠道信息
		PaymentChannelEntity pymentChannel = paymentChannelMapper.selectBychannelId(channelId);
		if (pymentChannel == null) {
			return setResultError("没有查询到该渠道信息");
		}

		// 2.使用payToken查询待支付信息
		BaseResponse<PayMentTransacDTO> tokenByPayMentTransac = payMentTransacInfoService
				.tokenByPayMentTransac(payToken);

		if (!isSuccess(tokenByPayMentTransac)) {
			return setResultSuccess(tokenByPayMentTransac.getMsg());
		}
		// 3.使用Java反射机制初始化子类
		String classAddres = pymentChannel.getClassAddres();
		PayStrategy payStrategy = StrategyFactory.getPayStrategy(classAddres);
		if (payStrategy == null) {
			return setResultError("支付系统网关错误!");
		}
		PayMentTransacDTO payMentTransacDTO = tokenByPayMentTransac.getData();
		// 4.直接执行子类实现方法
		String payHtml = payStrategy.toPayHtml(pymentChannel, payMentTransacDTO);
		JSONObject data = new JSONObject();
		data.put("payHtml", payHtml);
		return setResultSuccess(data);
	}

}
